import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_reactive_ble/flutter_reactive_ble.dart';
import 'package:get/get.dart';
import 'package:mziot/app/config/design.dart';
import 'package:mziot/app/modules/home/controllers/home_controller.dart';
import 'package:mziot/app/routes/app_pages.dart';
import 'package:mziot/app/tools/blue_service.dart';
import 'package:mziot/app/tools/tools.dart';
import 'package:mziot/generated/assets.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class DevicesListView extends GetView<HomeController> {
  final groupList;

  DevicesListView(this.groupList);

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(top: groupList ? 0 : 16),
      padding: EdgeInsets.symmetric(horizontal: 12),
      child: Obx(() {
        var list = groupList ? controller.groupDeviceList.value : controller.deviceList.value;

        return groupList
            ? GridView.builder(
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2,
                  mainAxisSpacing: 15,
                  crossAxisSpacing: 15,
                  childAspectRatio: 168.0 / 164,
                ),
                itemCount: list.length + 1,
                itemBuilder: (ctx, index) {
                  if (index < list.length) {
                    return _deviceItem(index);
                  } else {
                    return _emptyView;
                  }
                },
              )
            : SmartRefresher(
                controller: controller.refreshController,
                onRefresh: () => controller.refreshAction(),
                onLoading: () => controller.loadMore(),
                child: GridView.builder(
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 2,
                    mainAxisSpacing: 15,
                    crossAxisSpacing: 15,
                    childAspectRatio: 168.0 / 164,
                  ),
                  itemCount: list.length + 1,
                  itemBuilder: (ctx, index) {
                    if (list.length == index) {
                      return _emptyView;
                    }

                    return _deviceItem(index);
                  },
                ),
              );
      }),
    );
  }

  bool checkEnable(int index) {
    var disEnable = true;
    if (groupList) {
      final lock = controller.groupDeviceList[index].isLock.value;
      final isWifi = controller.groupDeviceList[index].isWifi.value;
      final isBlue = controller.groupDeviceList[index].isBluetooth.value;
      disEnable = lock || (!isWifi && !isBlue);
    } else {
      if (index < controller.deviceList.value.length) {
        final lock = controller.deviceList[index].isLock.value;
        final isWifi = controller.deviceList[index].isWifi.value;
        final isBlue = controller.deviceList[index].isBluetooth.value;
        disEnable = lock || (!isWifi && !isBlue);
      }
    }

    return disEnable;
  }

  Widget _deviceItem(int index) {
    return GestureDetector(
      onLongPress: () {
        if (groupList) {
          final model = controller.groupDeviceList.value[index];
          if (model.isLock.value) {
            return;
          }
          controller.deleteConfirm(model.id);
        } else {
          final model = controller.deviceList.value[index];
          if (model.isLock.value) {
            return;
          }
          final id = model.id;
          if ((!model.isBluetooth.value ||
                  BlueService.share.deviceState != DeviceConnectionState.connected) &&
              !model.isWifi.value) {
            controller.deleteAlert(id!);
            return;
          }
          controller.deleteConfirm(id);
        }
      },
      onTap: () {
        if (checkEnable(index)) {
          return;
        }
        controller.toLighting(index);
      },
      child: Obx(() {
        bool isEnable = checkEnable(index);
        return Container(
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(15),
            color: isEnable ? Colors.white.withOpacity(0.5) : Colors.white,
          ),
          padding: EdgeInsets.all(12),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  _markView(index),
                  CachedNetworkImage(
                    imageUrl: groupList
                        ? controller.groupDeviceList[index].deviceImg ?? ''
                        : controller.deviceList[index].deviceImg ?? '',
                    width: 45,
                    height: 45,
                    fit: BoxFit.fill,
                  ),
                  _progress(index),
                ],
              ),
              SizedBox(height: 8),
              Text(
                groupList
                    ? controller.groupDeviceList[index].deviceName ?? '-'
                    : controller.deviceList[index].deviceName ?? '-',
                style: MFont.regular13.apply(color: MColor.xFF333333),
                maxLines: 1,
              ),
              Text(
                groupList
                    ? controller.groupDeviceList[index].sceneName ?? '-'
                    : controller.deviceList[index].sceneName ?? '-',
                style: MFont.regular11.apply(color: MColor.xFF999999),
              ),
              _toolView(index),
            ],
          ),
        );
      }),
    );
  }

  Widget _markView(index) {
    bool? lockStatus;
    bool isWifi = false;
    String? image;
    if (groupList) {
      lockStatus = controller.groupDeviceList[index].isLock.value;
      isWifi = controller.groupDeviceList[index].isNetDevice ?? false;
    } else {
      if (index >= controller.deviceList.length) {
        return Container();
      }
      lockStatus = controller.deviceList[index].isLock.value;
      isWifi = controller.deviceList[index].isNetDevice ?? false;
    }
    if (lockStatus == true && isWifi) {
      image = Assets.imagesDeviceWifiLock;
    } else if (lockStatus == true) {
      image = Assets.imagesDeviceLock;
    } else if (isWifi) {
      image = Assets.imagesDeviceWifi;
    }
    if (image == null) {
      return Container(width: 44);
    }
    return Container(
      height: 20,
      width: 44,
      child: Image.asset(image),
    );
  }

  Widget _progress(int index) {
    return Obx(() {
      int? rate = 0;
      if (groupList) {
        rate = controller.groupDeviceList[index].lightRate.value;
      } else {
        if (index < controller.deviceList.length) {
          rate = controller.deviceList[index].lightRate.value;
        }
      }

      if (rate < 0) {
        return Container(
          width: 44,
          height: 44,
        );
      }

      return Container(
        width: 44,
        height: 44,
        padding: EdgeInsets.only(left: 14, bottom: 14),
        child: Stack(
          alignment: Alignment.center,
          children: [
            CircularProgressIndicator(
              value: rate / 100,
              strokeWidth: 2,
              backgroundColor: MColor.xFFEEEEEE,
              valueColor: AlwaysStoppedAnimation<Color>(MColor.xFFFFA433),
            ),
            Align(
              alignment: Alignment.center,
              child: Text(
                '$rate%',
                style: MFont.regular10.apply(color: MColor.xFFFFA433),
              ),
            )
          ],
        ),
      );
    });
  }

  Widget _checkView(int index) {
    return Obx(() {
      var selected = false;
      if (groupList) {
        selected = controller.groupDeviceList[index].isSelected.value;
      } else {
        if (index >= controller.deviceList.length) {
          return Container();
        }
        selected = controller.deviceList[index].isSelected.value;
      }

      return Container(
        padding: EdgeInsets.all(7.5),
        decoration: BoxDecoration(
          color: selected ? MColor.skin : MColor.xFFEEEEEE,
          borderRadius: BorderRadius.circular(15),
        ),
        child: Icon(
          Icons.check,
          size: 15,
          color: selected ? Colors.white : MColor.xFFEEEEEE,
        ),
      );
    });
  }

  Widget _toolView(int index) {
    return Obx(() {
      bool lockStatus = false;
      bool isClose = false;
      bool isWifi = false;
      bool isBluetooth = false;

      if (groupList) {
        lockStatus = controller.groupDeviceList[index].isLock.value;
        isClose = controller.groupDeviceList[index].closeState.value;
        isWifi = controller.groupDeviceList[index].isWifi.value;
        isBluetooth = controller.groupDeviceList[index].isBluetooth.value;
      } else {
        if (index >= controller.deviceList.length) {
          return Container();
        }
        lockStatus = controller.deviceList[index].isLock.value;
        isClose = controller.deviceList[index].closeState.value;
        isWifi = controller.deviceList[index].isWifi.value;
        isBluetooth = controller.deviceList[index].isBluetooth.value;
      }

      bool disAble = (!isWifi && !isBluetooth) || lockStatus;
      Widget iconButton(String name, int buttonIndex) {
        double alpha = 0.5;
        if (buttonIndex == 0) {
          alpha = 1;
        } else {
          alpha = disAble ? 0.5 : 1;
        }
        return Opacity(
          opacity: alpha,
          child: IconButton(
            onPressed: () {
              if (buttonIndex == 1) {
                if (!disAble) {
                  throttle(() {
                    controller.fetchSwitchDevices(index, groupList,
                        device: groupList
                            ? controller.groupDeviceList[index]
                            : controller.deviceList[index]);
                  });
                }
              } else {
                Get.toNamed(
                  Routes.DEVICE_MANAGER,
                  arguments: {
                    'group': false,
                    'add': false,
                    'data': groupList
                        ? controller.groupDeviceList[index]
                        : controller.deviceList[index],
                  },
                )?.then((value) {
                  if (groupList) {
                    controller.fetchGroupDevices();
                  } else {
                    controller.refreshAction();
                    controller.fetchDevices();
                  }
                });
              }
            },
            iconSize: 50,
            icon: Image.asset(
              name,
              width: 32,
              height: 32,
            ),
            constraints: BoxConstraints(maxHeight: 50),
          ),
        );
      }

      return Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          iconButton(Assets.imagesDeviceSetting, 0),
          Spacer(),
          IgnorePointer(
            ignoring: disAble,
            child: iconButton(
              !isClose ? Assets.imagesDeviceOpen : Assets.imagesDeviceClose,
              1,
            ),
          ),
        ],
      );
    });
  }

  get _emptyView {
    return Container(
      width: double.infinity,
      child: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          if (groupList) {
            controller.fetchAllDevices();
            return;
          }
          Get.toNamed(Routes.ADD_DEVICE)?.then((value) {
            BlueService.share.isAll = false;
            controller.refreshAction();
          });
        },
        child: Center(
          child: Container(
            width: 64,
            height: 64,
            decoration: BoxDecoration(
              color: Colors.white.withOpacity(0.2),
              borderRadius: BorderRadius.circular(32),
            ),
            child: Center(child: Image.asset(Assets.imagesListInsert, width: 32, height: 32)),
          ),
        ),
      ),
    );
  }
}
